package com.mpj.yolov12

import android.util.Log
import org.json.JSONException
import org.json.JSONObject
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
import kotlin.concurrent.thread

/**
 * UDP广播监听器
 */
class UdpBroadcastListener(private var portin: Int = 8888) {

    private var socket: DatagramSocket? = null
    private var isListening = false
    private var listenerThread: Thread? = null

    // 消息回调
    var onMessageReceived: ((message: String, senderIp: String, senderPort: Int) -> Unit)? = null

    /**
     * 开始监听广播
     */
    fun startListening() {
        if (isListening) return

        try {
            socket = DatagramSocket(null).apply {
                reuseAddress = true
                Log.d("pw$portin", "$portin")
                bind(InetSocketAddress(portin))
            }

            isListening = true

            listenerThread = thread {
                Log.d("UDP", "开始监听UDP广播，端口: $portin")

                while (isListening) {
                    try {
                        val buffer = ByteArray(2000)
                        val packet = DatagramPacket(buffer, buffer.size)
                        socket?.receive(packet)

                        val data = packet.data.copyOfRange(0, packet.length)
                        val message = String(data, StandardCharsets.UTF_8)
                        val udpPort = parseUdpPort(message)
                        val senderIp = packet.address.hostAddress

                        // 回调通知接收到消息
                        onMessageReceived?.invoke(message, senderIp!!, udpPort!!)

                        // 重置数据包
                        packet.length = buffer.size
                    } catch (e: Exception) {
                        if (isListening) {
                            Log.e("UDP", "接收广播出错: ${e.message}")
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("UDP", "启动监听器失败: ${e.message}")
            stopListening()
        }
    }


    fun parseUdpPort(jsonString: String): Int? {
        return try {
            val jsonObject = JSONObject(jsonString)
            if (jsonObject.has("udp_port")) {
                jsonObject.getInt("udp_port")
            } else {
                null
            }
        } catch (e: JSONException) {
            Log.e("JSON解析", "解析错误: ${e.message}")
            null
        }
    }

    /**
     * 停止监听
     */
    fun stopListening() {
        isListening = false
        socket?.close()
        socket = null
        Log.d("UDP", "UDP广播监听已停止")
    }

    /**
     * 检查是否正在监听
     */
    fun isListening(): Boolean {
        return isListening
    }
}
